#!/usr/bin/env bash

project_path=$(
	cd $(dirname $0)
	cd ..
	pwd
)
cd $project_path/

#工程名
project_name=$1

#scheme名
scheme_name=$2

#打包模式 Debug/Release/Enterprise
development_mode=$3

#plist文件名称
plist_name=$4

#是否显示打印日志
show_log=$5

#build文件夹路径
build_path=${project_path}/build

#plist文件所在路径
exportOptionsPlistPath=${project_path}/1_AutoArchive/$plist_name.plist

#导出.ipa文件所在路径
exportIpaPath=${project_path}/1_AutoArchive/ipas/$project_name-IPA/${development_mode}/$(date +"%Y%m%d")/$(date +"%H-%M-%S")
if [ ! -d $exportIpaPath ]; then
	mkdir -p $exportIpaPath
fi

echo '-----------'
echo ' 正在编译工程:'${development_mode}
echo '-----------'
echo ''

if [ $show_log = "yes" ]; then
	xcodebuild archive -workspace ${project_path}/${project_name}.xcworkspace -scheme ${scheme_name} -configuration ${development_mode} -archivePath ${build_path}/${project_name}.xcarchive -quiet || exit
else
	xcodebuild >/dev/null archive -workspace ${project_path}/${project_name}.xcworkspace -scheme ${scheme_name} -configuration ${development_mode} -archivePath ${build_path}/${project_name}.xcarchive -quiet || exit
fi

echo '--------'
echo ' 编译完成'
echo '--------'
echo ''

echo '----------'
echo ' 开始ipa打包'
echo '----------'
echo ''

# > /dev/null不输出打包信息
if [ $show_log = "yes" ]; then
	xcodebuild -exportArchive -archivePath ${build_path}/${project_name}.xcarchive -configuration ${development_mode} -exportPath ${exportIpaPath} -exportOptionsPlist ${exportOptionsPlistPath} -quiet || exit
else
	xcodebuild >/dev/null -exportArchive -archivePath ${build_path}/${project_name}.xcarchive -configuration ${development_mode} -exportPath ${exportIpaPath} -exportOptionsPlist ${exportOptionsPlistPath} -quiet || exit
fi

if [ -e $exportIpaPath/$scheme_name.ipa ]; then

	echo '----------'
	echo ' ipa包已导出'
	echo '----------'
	echo ''

else

	echo '-------------'
	echo ' ipa包导出失败 '
	echo '-------------'
	echo ''

fi

echo '----------'
echo ' 备份dSYM文件'
echo '----------'
echo ''

cp -R $build_path/${project_name}.xcarchive/dSYMs/${scheme_name}.app.dSYM $exportIpaPath

echo '----------'
echo ' 清除build文件'
echo '----------'
echo ''

rm -rf $build_path || exit

echo '----------'
echo ' 复制ipa文件，准备上传服务器'
echo '----------'
echo ''

scp $exportIpaPath/$scheme_name.ipa $project_path/1_AutoArchive/ipas/app.ipa || exit

exit 0
